﻿namespace JobButenko.Models.BusinessLogicLayer
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    public class EmployedJobRepository
    {
        private readonly JobDataContext dataContext;

        public EmployedJobRepository(JobDataContext dataContext)
        {
            this.dataContext = dataContext;
        }

        private EmployedJob GetEmployerJob(int vacancyId, int candidateId)
        {
            return
                this.dataContext.EmployedJobs.SingleOrDefault(
                    e => e.CandidateId.Equals(candidateId) && e.VacancyId.Equals(vacancyId));
        }

        public bool AddEmployedJob(int vacancyId)
        {
            var dataManager = new DataManager();
            var candidateId =
                dataManager.Candidate.GetCandidateFromUserName(HttpContext.Current.User.Identity.Name).CandidateId;
            if (this.GetEmployerJob(vacancyId, candidateId) == null)
            {
                var employedJob = new EmployedJob
                                      {
                                          CandidateId = candidateId,
                                          VacancyId = vacancyId
                                      };

                this.dataContext.EmployedJobs.InsertOnSubmit(employedJob);
                this.dataContext.SubmitChanges();
                return true;
            }

            return false;
        }

        public void DelEmployedJob(int vacancyId)
        {
            var dataManager = new DataManager();
            var candidateId =
                dataManager.Candidate.GetCandidateFromUserName(HttpContext.Current.User.Identity.Name).CandidateId;
            this.dataContext.EmployedJobs.DeleteOnSubmit(this.GetEmployerJob(vacancyId, candidateId));
            this.dataContext.SubmitChanges();
        }

        public List<EmployedJob> GetAddCandidateVacancy()
        {
            var dataManager = new DataManager();
            var candidateId =
                dataManager.Candidate.GetCandidateFromUserName(HttpContext.Current.User.Identity.Name).CandidateId;
            return this.dataContext.EmployedJobs.Where(e => e.CandidateId.Equals(candidateId)).ToList();
        }

        public List<EmployedJob> GetCandidateAddVacancy()
        {
            var dataManager = new DataManager();
            var employer =
                dataManager.Employer.GetEmployerFromUserName(HttpContext.Current.User.Identity.Name).EmpoyerId;
            return this.dataContext.EmployedJobs.Where(e => e.Vacancy.Employer.EmpoyerId.Equals(employer)).ToList();
        }
    }
}